package org.dexter.model.vo
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;
	import flash.utils.describeType;
	import flash.utils.getQualifiedClassName;

	public class VOBase extends EventDispatcher
	{
		private var vars:XMLList;
		public function convertFromObject(o:Object):void
		{
			if(o){
				if(o is String)o = JSON.decode(o as String);
				vars = describeType(this).variable;
				for(var i:String in o){
					try{
						if(this[i] is VOBaseArray){
							if(o[i] is String)(this[i] as VOBaseArray).setArray(JSON.decode(o[i]));
							else (this[i] as VOBaseArray).setArray(o[i]);
						}else if(this[i] is VOBase){
							this[i].convertFromObject(o[i]);
						}else if(o[i]!=null){
							this[i] = o[i];
						}
					}catch(e:Error){
						convertError(i,o[i]);
					}
				}
			}
		}
		protected function convertError(key:String,value:*):void{
			ExternalInterface.call("alert",key);
			ExternalInterface.call("alert",value);
//			trace(getQualifiedClassName(this),key,value);
		}
		protected function convertToObjectWay(name:String):Object{
			var value:Object = this[name];
			if(value is Array)
				return convertArrayToObject(value as Array);
			return null;
		}
		public function convertToObject():Object{
			var o:Object = {};
			if(!vars)vars = describeType(this).variable;
			for each(var i:XML in vars){
				var value:Object = this[i.@name];
				var type:String = typeof(value);
				switch (type){
					case "number":
					case "string":
						o[i.@name] = value;
						break;
					case "boolean":
						o[i.@name] = Number(value);
						break;
					case "object":
					default:
						o[i.@name] = convertToObjectWay(i.@name);
						break;
				}
			}
			return o;
		}
		public function convertArrayToObject(array:Array):Array{
			var result:Array = [];
			for each(var o:VOBase in array)
				if(o)result.push(o.convertToObject());
			return result;
		}
		public function convertArrayFromObject(array:Array,c:Class):void{
			if(!array)return;
			for(var i:int;i<array.length;i++){
				var vo:VOBase = new c() as VOBase;
				vo.convertFromObject(array[i]);
				array[i] = vo;
			}
		}
	}
}